#include "floracommunityserial.h"
#include "FloraLogger.h"
#include <QElapsedTimer>
floraCommunitySerial::floraCommunitySerial()
{
    isConnected = false;
}

void floraCommunitySerial::configure(QString &portName, int baudRate, QSerialPort::DataBits dataBits, QSerialPort::Parity parity, QSerialPort::StopBits stopBits, QSerialPort::FlowControl flowControl)
{

    m_portName = portName; // 保存参数到成员变量
    m_baudRate = baudRate;
    m_dataBits = dataBits;
    m_parity = parity;
    m_stopBits = stopBits;
    m_flowControl = flowControl;
    for(int i=0 ;i<200;i++)
    {
        communitError[i] = 0;
    }
}

void floraCommunitySerial::appendBurstCommand(commandTuple comand)
{
    if(!isConnected)return;
    brust_mutex.lock();
    burstCommandQue.append(comand);
    brust_mutex.unlock();
}

bool floraCommunitySerial::openPort()
{

}

void floraCommunitySerial::closePort()
{

}

void floraCommunitySerial::run()
{
    int ret;
    int loopCommandCount = 0;
    bool have_loop_command;
    bool have_brust_command;

    LOG_DEBUG<<busName<<"开始执行";
    commandTuple tempLoopCommand;
    commandTuple brustCommand;

    QSerialPort serialPort;

    serialPort.setPortName(m_portName);
    serialPort.setBaudRate(m_baudRate);
    serialPort.setDataBits(m_dataBits);
    serialPort.setParity(m_parity);
    serialPort.setStopBits(m_stopBits);
    serialPort.setFlowControl(m_flowControl);


    if (serialPort.open(QIODevice::ReadWrite)) {
        LOG_DEBUG <<"线程:"<<busName<<":串口 "<<m_portName<< "    Port opened successfully.";
        ret =  true;
        isConnected = true;
    } else {
        LOG_DEBUG <<"线程:"<<busName<<":串口 "<<m_portName<< "    Failed to open port  !!!!!!!!!!!!!!!!!!!!!!!";
        ret =  false;
        isConnected = false;
    }
    if(ret == false)return;
    while(running)
    {
        // 取一条循环命令
        mutex.lock();
        if(loopCommandVec.size()>0)
        {
            if(loopCommandCount >= loopCommandVec.size())
            {
                loopCommandCount = 0;
            }
            tempLoopCommand = loopCommandVec[loopCommandCount];
            loopCommandCount ++;
            have_loop_command = true;
        }
        else
        {
            have_loop_command = false;
        }
        mutex.unlock();
        if(have_loop_command)
        {
            int dev_addr = std::get<0>(tempLoopCommand);  // 访问第一个元素
            int command_type = std::get<1>(tempLoopCommand); // 访问第二个元素
            QByteArray command_bytes = std::get<2>(tempLoopCommand); // 访问第三个元素
            if(communitError[dev_addr]>10)
            {
                //continue;
            }
            serialPort.write(command_bytes);
            serialPort.waitForBytesWritten(1000);
            QByteArray bytes;
            if(serialPort.waitForReadyRead(20))
            {
                bytes = serialPort.readAll();
                emit loopCommandResponse(dev_addr,command_type,bytes);
            }
            else
            {
                communitError[dev_addr]++;
                emit loopCommandResponse(dev_addr,command_type,bytes);
            }
        }
        // 取一条突发命令
        while(1)
        {
            brust_mutex.lock();
            if(!burstCommandQue.isEmpty())
            {
                have_brust_command = true;
                brustCommand = burstCommandQue.dequeue();
            }
            else
            {
                have_brust_command = false;
            }
            brust_mutex.unlock();
            if(have_brust_command)
            {

                int dev_addr = std::get<0>(brustCommand);  // 访问第一个元素
                int command_type = std::get<1>(brustCommand); // 访问第二个元素
                QByteArray command_bytes = std::get<2>(brustCommand); // 访问第三个元素
                if(communitError[dev_addr]>10)
                {
                    LOG_DEBUG<<"跳出"<<dev_addr<<communitError[dev_addr];
                      continue;
                }
                serialPort.write(command_bytes);
                QElapsedTimer timer; // 创建一个 QElapsedTimer 对象
                timer.start(); // 启动计时器
                serialPort.waitForBytesWritten(1000);
                if(command_type<0)
                {
                    LOG_DEBUG<<"send data"<<command_bytes.toHex(' ');
                    msleep(5);
                    continue;
                }
                LOG_DEBUG<<"send data"<<command_bytes.toHex(' ');
                QByteArray bytes;
                if (serialPort.waitForReadyRead(10))
                {
                    bytes = serialPort.readAll();
                    emit burstCommandResponse(dev_addr,command_type,bytes);
                    qint64 elapsed = timer.elapsed(); // 获取已过去的毫秒数
                    communitError[dev_addr] = 0;
                    LOG_DEBUG << "Command executed in" << elapsed << "milliseconds";
                }
                else
                {
                    communitError[dev_addr]++;
                    emit burstCommandResponse(dev_addr,command_type,bytes);
                }
            }
            else
            {
                break;
            }
        }
    }
    serialPort.close();
}
